<template>
  <div class="order-detail-page">
    <div v-if="loading" class="loading-container">
      <el-icon class="loading-icon" :size="50"><Loading /></el-icon>
      <p>加载订单详情中...</p>
    </div>

    <div v-else-if="order" class="order-container">
      <!-- 订单概览 -->
      <el-card class="order-summary">
        <div class="order-header">
          <h2>订单号：{{ order.order_id }}</h2>
          <el-tag :type="statusTagType" effect="dark">
            {{ order.order_status }}
          </el-tag>
        </div>

        <div class="order-meta">
          <div class="meta-item">
            <span class="meta-label">下单时间：</span>
            {{ formatDate(order.created_at) }}
          </div>
          <div class="meta-item">
            <span class="meta-label">支付方式：</span>
            {{ order.payment_method || '虚拟货币' }}
          </div>
          <div class="meta-item total-amount">
            <span class="meta-label">订单总额：</span>
            <span class="amount">¥{{ order.total_amount }}</span>
          </div>
        </div>
      </el-card>

      <!-- 商品清单 -->
      <el-card class="goods-list">
        <template #header>
          <h3>商品清单</h3>
        </template>
        
        <el-table :data="orderDetails" stripe>
          <el-table-column prop="product_name" label="商品名称" width="300" />
          <el-table-column label="单价" width="120">
            <template #default="scope">
              ¥{{ scope.row.price.toFixed(2) }}
            </template>
          </el-table-column>
          <el-table-column prop="quantity" label数量 width="100" />
          <el-table-column label="小计" width="150">
            <template #default="scope">
              ¥{{ (scope.row.price * scope.row.quantity).toFixed(2) }}
            </template>
          </el-table-column>
        </el-table>
      </el-card>

      <!-- 操作按钮 -->
      <div class="action-buttons">
        <el-button 
          v-if="order.order_status === 'pending'"
          type="danger" 
          @click="handleCancelOrder"
        >
          取消订单
        </el-button>
        <el-button @click="$router.go(-1)">
          返回订单列表
        </el-button>
      </div>
    </div>

    <div v-else class="empty-container">
      <el-empty description="订单不存在或已删除">
        <el-button @click="$router.push('/admin/Order')">返回订单列表</el-button>
      </el-empty>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRoute } from 'vue-router'
import axios from 'axios'
import { ElNotification } from 'element-plus'
import { Loading } from '@element-plus/icons-vue'

const route = useRoute()
const order = ref(null)
const orderDetails = ref([])
const loading = ref(true)

// 状态标签样式
const statusTagType = computed(() => {
  const map = {
    completed: 'success',
    pending: 'warning',
    cancelled: 'info'
  }
  return map[order.value?.order_status?.toLowerCase()] || ''
})

// 获取订单详情
const fetchOrderDetail = async () => {
  try {
    const token = localStorage.getItem('token')
    const response = await axios.get(
      `http://localhost:3000/orders/${route.params.orderId}`,
      { headers: { Authorization: `Bearer ${token}` } }
    )
    
    order.value = response.data.order
    orderDetails.value = response.data.details
  } catch (error) {
    ElNotification.error({
      title: '错误',
      message: error.response?.data?.error || '获取订单详情失败'
    })
  } finally {
    loading.value = false
  }
}

// 取消订单
const handleCancelOrder = async () => {
  try {
    await axios.post(
      `http://localhost:3000/orders/cancel/${order.value.order_id}`,
      {},
      { headers: { Authorization: `Bearer ${localStorage.getItem('token')}` } }
    )
    
    await fetchOrderDetail()
    ElNotification.success('订单已取消')
  } catch (error) {
    ElNotification.error('取消订单失败')
  }
}

// 时间格式化
const formatDate = (timestamp) => {
  return new Date(timestamp).toLocaleString()
}

onMounted(() => {
  fetchOrderDetail()
})
</script>

<style scoped>
.order-detail-page {
  max-width: 1200px;
  margin: 20px auto;
  padding: 0 20px;
}

.loading-container {
  text-align: center;
  padding: 50px 0;
}

.loading-icon {
  animation: rotating 2s linear infinite;
  margin-bottom: 20px;
}

@keyframes rotating {
  from { transform: rotate(0deg); }
  to { transform: rotate(360deg); }
}

.order-summary {
  margin-bottom: 20px;
}

.order-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.order-meta {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 20px;
}

.meta-item {
  padding: 10px;
  background: #f5f7fa;
  border-radius: 4px;
}

.meta-label {
  color: #909399;
}

.total-amount .amount {
  font-size: 18px;
  color: #e4393c;
  font-weight: bold;
}

.goods-list {
  margin-bottom: 30px;
}

.action-buttons {
  text-align: right;
  padding: 20px 0;
}

.empty-container {
  margin-top: 100px;
}
</style>